<?php
/**
 * Created by PhpStorm.
 * User: wanglin
 * Date: 2018/9/12
 * Time: 15:58
 */

namespace App\Services\ThirdAPI;



use App\Models\Game;
use App\Models\MgGames;
use common\utils\RedisKeys;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use common\enum\CommonEnum;
use common\utils\SysCode;

class MGAPIService
{


    protected $apiName = "MG";



    /**
     * 获取MG游戏名称
     */
    public function getMGGameNames()
    {
        $data = Game::where(['partner_name' => $this->apiName])->get()->toArray();
        $needUpdate = Redis::set(RedisKeys::MG_LOCK_GAMES, date("Y-m-d H:i:s"), 'nx', 'ex', 600);
        if (!$data || $needUpdate) {
            $data = $this->getMGGameLists();
        }
        $games = [];
        foreach ($data as $game) {
            $games[$game['game_code']] = $game['name'];
        }
        return $games;
    }


    /**
     * 获取MG电子游戏列表
     */
    public function getMGGameLists()
    {
        $currentData = Game::where(['partner_name' => $this->apiName])->get();
        if(!empty($currentData)){
            $currentData=$currentData->toArray();
        }
        $gameData = [];
        foreach ($currentData as $value) {
            $gameData[$value['game_code']] = $value;
        }
        $data = $this->requestGame();
        $partnerInfo = GameApiService::getApiPartnerInfoByName($this->apiName);
        $insertData = [];
        foreach ($data as $values) {
            if (empty($gameData[$values['gameId']])) {
                $insertData[] = [
                    'partner_id' => $partnerInfo['id'],
                    'partner_name' => $partnerInfo['name'],
                    'name' => $values['gameName'],
                    'img_url' => $values['gameImg'],
                    'game_code' => $values['gameId'],
                    'type' => $values['category'],
                    'device'=> $values['gameType'],
                    'extend' => $values['gameCode'],
                    'game_type' => CommonEnum::GAME_EGAME, // 电子游戏
                ];
            }
        }
        if (count($insertData) > 0) {
            $res= GameApiService::saveGame($insertData);
            if (!$res) {
                Redis::del(RedisKeys::MG_LOCK_GAMES);
                Log::error("MG MGAPIService::getMGGameList 保存游戏列表报错失败：" . json_encode($res->getErrors(), JSON_UNESCAPED_UNICODE));
                return error_exit(SysCode::INTERNAL_SERVER_ERROR, "MG MGAPIService::getMGGameList 保存游戏列表报错失败");
            }
        }
        $currentData = array_merge($currentData, $insertData);
        return $currentData;
    }

    /**
     * 请求游戏列表
     * @param int $page
     * @param int $pageSize
     */
    public function requestGame()
    {
        $url = config('app.rpcserver') . "/api/getGameList";
        $res = GameApiService::request($url, "get", ['api_name' => $this->apiName]);
        return $res;
    }


    /**
     * 获取mg电子的相关注单
     * @param $startTime
     * @param $endTime
     * @param int $page
     * @param int $pageSize
     */
    public function getMGOrders($startTime, $endTime)
    {
        $result = [];
        $url = config('app.rpcserver') . "/api/getOrders";
        $data=[
            'api_name' => $this->apiName,
            'start_time' => $startTime+3600*4,//因为接口限制，开始时间和结束时间必须大于一分钟，接口数据延迟十分钟左右，查询往前十分钟
            'end_time' => $endTime+3600*4,
        ];
        Log::info("请求url:".$url . "请求开始时间参数:".date("Y-m-d H:i:s",$data['start_time'])  . "=请求结束时间:" . date("Y-m-d H:i:s",$data['end_time']));
        $res = GameApiService::request($url, "get", $data);
        $result =array_merge($result, $res);
        Log::info("MG视讯注单抓取接口请求url:====" . $url . "请求参数:======" . json_encode($data, JSON_UNESCAPED_UNICODE) . "请求时间:====" . date("Y-m-d H:i:s") . "总共有" . count($result) . "条数据");
        amount_format_array($result,['bet_money','winloss_money','prize_money','valid_money','contribute_money','bonus_money'],true);
        return $result;
    }
}